package MyText;

public class HashBuck<K, V> {

    class Node<K, V> {
        public K key;
        public V val;
        public Node<K, V> next;

        public Node(K key, V val) {
            this.key = key;
            this.val = val;
        }
    }

    public Node<K, V>[] arr;
    public int usesize;
    public static final float DEFAULT = 0.75f;

    public HashBuck() {
        arr = (Node<K, V>[]) new Node[10];
    }

    private boolean search() {
        return usesize/arr.length>=DEFAULT;
    }

    private void resize(){
        Node<K, V>[] newarr = new Node[2*arr.length];
        for (int i = 0; i < arr.length; i++) {
            Node cur=arr[i];
            while(cur!=null){
                Node tmp=cur.next;
                int newindex=cur.key.hashCode()% newarr.length;
                cur.next=newarr[newindex];
                newarr[newindex]=cur;
                cur=tmp;
            }
        }
      arr=newarr;
    }

    public void put(K key, V val) {
        int hash = key.hashCode();
        int index = hash % arr.length;
        Node<K, V> cur = arr[index];
        while (cur != null) {
            if (cur.key == key) {
                cur.val = val;
                break;
            }
            cur = cur.next;
        }
        Node<K, V> node = new Node(key, val);
        node.next = arr[index];
        arr[index] = node;
        usesize++;
        if(search()){
            resize();
        }
    }

    public V get(K key){
        int hash = key.hashCode();
        int index = hash % arr.length;
        Node<K, V> cur = arr[index];
        while(cur!=null){
            if(cur.key==key){
                return cur.val;
            }
            cur=cur.next;
        }
        return null;
    }
}
